package org.hank.wanandroid.ui

import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Lifecycle
import kotlinx.android.synthetic.main.activity_main.*
import org.hank.commom.base.BaseActivity
import org.hank.wanandroid.R
import org.hank.wanandroid.ui.fragment.*

class MainActivity : BaseActivity() {
    override val layoutResId: Int
        get() = R.layout.activity_main

    var lastIndex = -1
    var fargmentList: MutableList<Fragment> = ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initFragment()
        main_navigation.setOnNavigationItemSelectedListener {
            when (it.itemId) {
                R.id.menu_home -> {
                    showFragment(0)
                }
                R.id.menu_project -> {
                    showFragment(1)
                }
                R.id.menu_square -> {
                    showFragment(2)
                }
                R.id.menu_official_account -> {
                    showFragment(3)
                }
                R.id.menu_mine -> {
                    showFragment(4)
                }
            }
            true
        }
    }

    fun initFragment() {
        fargmentList.add(HomePageFragment())
        fargmentList.add(ProjectPageFragment())
        fargmentList.add(SquareFragment())
        fargmentList.add(WxPageFragment())
        fargmentList.add(MinFragment())
        showFragment(0)
    }

    fun showFragment(position: Int) {
        val ft: FragmentTransaction = supportFragmentManager.beginTransaction()
        val currentFragment: Fragment = fargmentList[position]
        if (lastIndex != -1) {
            val lastFragment: Fragment = fargmentList[lastIndex]
            ft.hide(lastFragment)
        }
        lastIndex = position
        if (!currentFragment.isAdded) {
            supportFragmentManager.beginTransaction().remove(currentFragment).commit()
            ft.add(R.id.main_frame_container, currentFragment)
            ft.setMaxLifecycle(currentFragment, Lifecycle.State.RESUMED)
        }
        ft.show(currentFragment)
        ft.commit()
    }

    override fun onDestroy() {
        super.onDestroy()
    }
}